package com.concurrency.example.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class CopyOnWriteArrayListExample1 {
    private static int client_total = 5000;
    private static int thread_total = 200;
    private static List<Integer> list = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws Exception{
        ExecutorService excutor = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(thread_total);
        final CountDownLatch countDownLatch = new CountDownLatch(client_total);
        for (int i = 0; i < client_total; i++) {
            excutor.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {

                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        excutor.shutdown();
        log.info("list的size: {}", list.size());
    }

    public static void add() {
        list.add(1);
    }
}
